import os

import oss2
from django.conf import settings

class AliyunOSS:
    def __init__(self):
        # 从配置中加载 OSS 配置
        config = settings.ALIYUN_OSS_CONFIG
        self.auth = oss2.Auth(config['ACCESS_KEY_ID'], config['ACCESS_KEY_SECRET'])
        self.bucket = oss2.Bucket(self.auth, config['ENDPOINT'], config['BUCKET_NAME'])

    def upload_file(self, file_obj, file_name):
        """
        上传文件到阿里云 OSS
        :param file_obj: 文件对象 (可以是 Django 的 InMemoryUploadedFile)
        :param file_name: 上传到 OSS 的文件名（包含路径，例如 "folder/example.jpg"）
        :return: 文件的外链 URL
        """
        try:
            # 上传文件
            self.bucket.put_object(file_name, file_obj.read())
            local_upload_path = os.path.join(settings.MEDIA_ROOT, file_name)
            os.makedirs(os.path.dirname(local_upload_path), exist_ok=True)
            with open(local_upload_path, 'wb') as local_file:
                for chunk in file_obj.chunks():
                    local_file.write(chunk)
            # 返回文件的外链 URL
            return f"https://{settings.ALIYUN_OSS_CONFIG['BUCKET_NAME']}.{settings.ALIYUN_OSS_CONFIG['ENDPOINT']}/{file_name}"
        except Exception as e:
            print(f"OSS 上传失败: {e}")
            return None



aliyun_oss = AliyunOSS()